package com.xuecheng.content.service;

import com.xuecheng.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

@Service
public class PublishPageService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @Async
    public void publishPage(Map map,Long courseBaseId) throws Exception {
        Template template = configuration.getTemplate("learing_article.ftl");
        String htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlStr.getBytes());
        String fileName="/pages/"+courseBaseId+".html";

        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioProperties.getBucket())
                .contentType("text/html")
                .object(fileName)
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(args);
    }
}
